package com.example.demo.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import lombok.extern.slf4j.Slf4j;

/**
 * 处理跨域请求的拦截器
 * @author admin
 *
 */
@Slf4j
/*@Order(1)
@WebFilter(filterName="accessfilter",urlPatterns="/*")*/
public class AccessFilter implements Filter{
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		log.info("跨域处理过滤器被创建...");
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		String uri = req.getRequestURI();
		
		log.debug("本次请求的uri---------->{}",uri);
		
		resp.setContentType("application/json");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		//加了这行代码表示如果请求头中包含header也允许跨域
		resp.addHeader("Access-Control-Allow-Headers", "token,accesstoken,Content-type");
		resp.addHeader("Access-Control-Allow-Origin", "*");
			
		
		chain.doFilter(request, response);
		
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.info("过滤器销毁");
	}

}
